package com.example.api.controller.app;

import com.example.api.dto.AddressDTO;
import com.example.api.query.AddressQuery;
import com.example.api.service.AddressService;
import com.example.api.utils.PageResult;
import com.example.api.utils.Result;
import com.example.api.utils.ThreadContextUtil;
import com.example.api.vo.AddressVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Api(tags = "地址接口")
@RestController
@RequestMapping("/app/address")
public class AddressController {
    @Resource
    AddressService addressService;

    @ApiOperation("查询地址")
    @GetMapping
    public Result<List<AddressVO>> find(AddressQuery addressQuery){ //addressQuery封装了查询的条件
        PageResult<AddressVO> page = addressService.find(addressQuery);
        return Result.ok("成功",page.getList(),page.getTotal());
    }

    @ApiOperation("查询默认收获地址")
    @GetMapping("/default")
    public Result<AddressVO> findDefaultAddress(){
        long customerId = ThreadContextUtil.getData();
        AddressVO addressVO = addressService.findDefaultAddress(customerId);
        if(addressVO==null){
            return Result.failure("缺少收获地址");
        }
        return Result.ok("成功",addressVO);
    }



    @ApiOperation("添加地址")
    @PostMapping
    public Result add(AddressDTO addressDTO){

        System.out.println(Thread.currentThread());
        System.out.println(ThreadContextUtil.getData());

        //?怎么获取到拦截器中解析出来的customerId??
        addressService.add(addressDTO);
        return Result.ok("添加成功");
    }


    @ApiOperation("根据id查询地址")
    @GetMapping("/{id}")
    public Result findById(@PathVariable long id){
        AddressVO addressVO = addressService.findById(id);
        return Result.ok("查询成功",addressVO);
    }



    @ApiOperation("编辑地址")
    @PutMapping("/{id}")
    public Result update(@PathVariable long id, AddressDTO addressDTO){
        addressService.update(id,addressDTO);
        return Result.ok("修改成功");
    }

    @ApiOperation("删除地址")
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable long id){
        addressService.deleteById(id);
        return Result.ok("删除成功");
    }
}
